//
//  ZNGCityPickerView.m
//  开店通
//
//  Created by 张浩 on 15/7/21.
//  Copyright (c) 2015年 张浩. All rights reserved.
//

#import "ZNGCityPickerView.h"

#import "MJExtension.h"
#import "UIImage+Extension.h"
#import "ZNGConstants.h"

#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"

#define ZNGCityPickerViewResourceBundle @"CityPicker.bundle"
#define ZNGCityPickerViewFrameworkResourceBundle @"Frameworks/ZNGLibrary.framework/CityPicker.bundle"
#define CityPickerSourcePath(bundlePath) [[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt" inDirectory:bundlePath]

@interface ZNGCityPickerView () <UIPickerViewDelegate, UIPickerViewDataSource>
{
    ZNGLocateModel * _selectedLocate;
}

@property (nonatomic, strong) UIPickerView *pickerView;

@property(nonatomic, strong)NSArray *provinceList;
@property(nonatomic, strong)NSArray *cityList;
@property(nonatomic, strong)NSArray *districtList;

@end

@implementation ZNGCityPickerView

- (ZNGLocateModel *)selectedLocate
{
    if (_selectedLocate == nil) {
        _selectedLocate = [[ZNGLocateModel alloc] init];
    }
    return _selectedLocate;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        self.frame = CGRectMake(0, 0, kScreenW, 250);

        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [cancelButton setBackgroundImage:[UIImage imageWithColor:kColor(204, 204, 204)] forState:UIControlStateNormal];
        [cancelButton setBackgroundImage:[UIImage imageWithColor:kColor(165, 165, 165)] forState:UIControlStateHighlighted];
        
        cancelButton.layer.cornerRadius = 15.f;
        cancelButton.layer.masksToBounds = YES;
        [self addSubview:cancelButton];
        
        [cancelButton makeConstraints:^(MASConstraintMaker *make){
            make.top.offset(10);
            make.size.equalTo(CGSizeMake(70, 30));
            make.left.offset(15);
        }];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];

        [sureBtn setBackgroundImage:[UIImage imageWithColor:kColor(241, 83, 83)] forState:UIControlStateNormal];
        [sureBtn setBackgroundImage:[UIImage imageWithColor:kColor(241, 55, 55)] forState:UIControlStateHighlighted];

        sureBtn.layer.cornerRadius = 15.f;
        sureBtn.layer.masksToBounds = YES;
        [self addSubview:sureBtn];
        
        [sureBtn mas_makeConstraints:^(MASConstraintMaker *make){
            make.top.offset(10);
            make.size.equalTo(CGSizeMake(70, 30));
            make.right.offset(-15);
        }];
        
        self.pickerView = [[UIPickerView alloc] init];
        self.pickerView.delegate = self;
        self.pickerView.dataSource = self;
        [self addSubview:self.pickerView];
        
        [self.pickerView makeConstraints:^(MASConstraintMaker *make){
            make.left.bottom.right.equalTo(0);
            make.height.equalTo(200);
        }];
        
        NSData *data = [NSData dataWithContentsOfFile:CityPickerSourcePath(ZNGCityPickerViewResourceBundle)];
        
        if (!data) {
            
            data = [NSData dataWithContentsOfFile:CityPickerSourcePath(ZNGCityPickerViewFrameworkResourceBundle)];
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        self.provinceList = [ZNGProvinceModel mj_objectArrayWithKeyValuesArray:dict];
        
        self.cityList = [self.provinceList[0] sub];
        
        self.districtList = [self.cityList[0] sub];
        
        self.selectedLocate.province = self.provinceList[0];

        self.selectedLocate.city = self.cityList[0];

        self.selectedLocate.district = self.districtList[0];
    }
    return self;
}


+ (instancetype)cityPickerWithSelecteAction:(ZNGCityPickerSelecteAction) selecteAction cancelAction:(ZNGCityPickerCancelAction)cancelAction
{
    ZNGCityPickerView *pickerView = [[self alloc] init];
    pickerView.selecteAction = selecteAction;
    pickerView.cancelAction = cancelAction;
    return pickerView;
}
- (void)cancelAction:(UIButton *)button
{
    if (self.cancelAction) {
        self.cancelAction();
    }
}

- (void)sureAction:(UIButton *)button
{
    if (self.selecteAction) {
        self.selecteAction(self.selectedLocate);
    }
}

- (void)setSelectedLocate:(ZNGLocateModel *)selectedLocate
{
    self.selectedLocate = selectedLocate;
    
    if (selectedLocate.province.name.length > 0) {
        for (int i = 0 ; i < self.provinceList.count; i++) {
            ZNGProvinceModel *province = self.provinceList[i];
            if ([province.name isEqualToString:selectedLocate.province.name]) {
                [self.pickerView reloadComponent:0];
                [self.pickerView selectRow:i inComponent:0 animated:NO];
                
                self.cityList = province.sub;
                
                self.cityList = [self.provinceList[i] sub];
                for (int j = 0; j < self.cityList.count; j++) {
                    ZNGCityModel *city = self.cityList[j];
                    if ([city.name isEqualToString:selectedLocate.city.name]) {
                        [self.pickerView reloadComponent:1];
                        [self.pickerView selectRow:j inComponent:1 animated:NO];
                        
                        self.districtList = [self.cityList[j] sub];
                        for (int k = 0; k < self.districtList.count; k++) {
                            ZNGDistrictModel *district = self.districtList[k];
                            if ([district.name isEqualToString:selectedLocate.district.name]) {
                                [self.pickerView reloadComponent:2];
                                [self.pickerView selectRow:k inComponent:2 animated:NO];
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.provinceList.count;
    }
    else if (component == 1) {
        if (self.cityList == nil) {
            self.cityList = [self.provinceList[0] sub];
        }
        return self.cityList.count;
    }
    else if (component == 2) {
        if (self.districtList == nil) {
            self.districtList = [self.cityList[0] sub];
        }
        return self.districtList.count;
    } else {
        return 0;
    }
}

#pragma mark - UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
//        adjustsFontSizeToFitWidth property to YES
        pickerLabel.minimumScaleFactor = 8.;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [self.provinceList[row] name];
            break;
        case 1:
            return [self.cityList[row] name];
            break;
        case 2:
            return [self.districtList[row] name];
            break;
        default:
            return  @"";
            break;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 0) {
        return kScreenW * 0.3;
    }
    else if (component == 1) {
        return kScreenW * 0.25;
    }
    else {
        return kScreenW * 0.45;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.cityList = [self.provinceList[row] sub];
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
        
        self.districtList = [self.cityList[0] sub];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:YES];
        
        self.selectedLocate.province = self.provinceList[row];
        self.selectedLocate.city = self.cityList[0];
        self.selectedLocate.district = self.districtList[0];
    }
    else if (component == 1) {
        self.districtList = [self.cityList[row] sub];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:YES];
        
        self.selectedLocate.city = self.cityList[row];
        self.selectedLocate.district = self.districtList[0];
    }
    else if (component == 2) {
        self.selectedLocate.district = self.districtList[row];
    }
}
@end
